package com.way.util;

import java.util.ArrayList;
import java.util.Set;

import android.content.Context;
import android.gesture.Gesture;
import android.gesture.GestureLibraries;
import android.gesture.GestureLibrary;
import android.gesture.Prediction;
import android.util.Log;

public class GestureLibraryManager {
	public static final String GESTURE_FILE = "gestures";
	private static GestureLibraryManager mGestureManager = null;
	private GestureLibrary mGestureLibrary;

	private GestureLibraryManager(Context context) {
		mGestureLibrary = GestureLibraries.fromPrivateFile(context,
				GESTURE_FILE);
		mGestureLibrary.load();
	}

	public static GestureLibraryManager getInstance(Context context) {
		if (mGestureManager == null)
			mGestureManager = new GestureLibraryManager(context);
		return mGestureManager;
	}

	public boolean load() {
		return mGestureLibrary.load();
	}

	public Set<String> getGestureEntries() {
		return mGestureLibrary.getGestureEntries();
	}

	public ArrayList<Gesture> getGestures(String entryName) {
		return mGestureLibrary.getGestures(entryName);
	}

	public String searchGesture(Gesture gesture) {
		// 从手势库中查询匹配的内容， 匹配结果可能包含多个相似的内容， 匹配度高的结果放在最前面
		Log.d("gesture","searchGesture gesture = " + gesture);
		ArrayList<Prediction> predictions = mGestureLibrary.recognize(gesture);
		if (predictions != null && predictions.size() > 0) {
			float level = GestureLevel.getLevel(gesture);
			Prediction prediction = predictions.get(0);
			Log.d("gesture", "gesture length :" + gesture.getLength()
					+ " level: " + level + " prediction.score = "
					+ prediction.score);
			if (prediction.score > level) {
				Log.d("gesture", "searchGesture  name :" + prediction.name);
				return prediction.name;
			} else {
				return "";
			}
		}
		return null;
	}

	public void removeGesture(String name) {
		ArrayList<Gesture> gestures = mGestureLibrary.getGestures(name);
		if (gestures == null || gestures.size() == 0)
			return;
		Gesture gesture = (Gesture) gestures.get(0);
		mGestureLibrary.removeGesture(name, gesture);
		mGestureLibrary.save();
	}

	public boolean updateGesture(String name, Gesture gesture) {
		if (gesture != null) {
			mGestureLibrary.addGesture(name, gesture);
			mGestureLibrary.save();
			return true;
		}
		return false;
	}

	public Gesture getGesture(String name) {
		ArrayList<Gesture> gestures = mGestureLibrary.getGestures(name);
		if (gestures == null || gestures.size() == 0)
			return null;
		return (Gesture) gestures.get(0);
	}
}
